package com.ptmall.app;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jauker.widget.BadgeView;
import com.ptmall.app.bean.SettingBean;
import com.ptmall.app.bean.model.db.Account;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.ui.activity.LoginActivity;
import com.ptmall.app.ui.fragment.CategoryFragment;
import com.ptmall.app.ui.fragment.HomePageFragment;
import com.ptmall.app.ui.fragment.Mefragment;
import com.ptmall.app.ui.fragment.ShopCarfragment;
import com.ptmall.app.base.BaseMvpFragment;
import com.ptmall.app.base.theme.Eyes;
import com.ptmall.app.crash.CrashManager;
import com.ptmall.app.utils.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {


    private static final String TAG = "MainActivity";
    private String[] mTitles;
    private int[] selector;
    public ViewPager mVpMain;
    private TabLayout mTlMain;
    private List<BaseMvpFragment> mFragmentList = new ArrayList<BaseMvpFragment>();
    private CategoryFragment mCategoryFragment;
    private int mFirstShowPage = 0;//首次进入显示
    int mNowPager = 0;//
    public ShopCarfragment mShopCarfragment;

    HomePageFragment mHomePageFragment;
    public BadgeView mBadgeView;
    public BadgeView mBadgeView2;

    public static String PEISONGFEI = "";
    public static String QISONG = "";
    public static String MANJIAN = "";
    public static String MEMBERID = "";

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            mVpMain.setCurrentItem(intent.getIntExtra("position", 0));
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //上线把install方法打开    增加使用体验
        install();
        setContentView(R.layout.activity_main);
        MEMBERID = SharedPreferenceUtil.getSharedStringData(this, "memberId");
        Eyes.setStatusBarLightMode(this, Color.WHITE);
        this.mTlMain = (TabLayout) findViewById(R.id.tl_main);
        this.mVpMain = (ViewPager) findViewById(R.id.vp_main);

        mCategoryFragment = new CategoryFragment();
        mShopCarfragment = new ShopCarfragment();
        mHomePageFragment = new HomePageFragment();
        mFragmentList.add(mHomePageFragment);
        mFragmentList.add(new CategoryFragment());
        mFragmentList.add(mShopCarfragment);
        mFragmentList.add(new Mefragment());

        selector = new int[]{R.drawable.main_tab_selector_home
                , R.drawable.main_tab_selector_category
                , R.drawable.main_tab_selector_shopcar
                , R.drawable.main_tab_selector_wo};
        mTitles = getResources().getStringArray(R.array.main_tab);

        mVpMain.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }

            @Override
            public int getCount() {
                return mTitles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTitles[position];
            }
        });


        mVpMain.setOnTouchListener(((v, event) -> {
            v.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        }));


        mVpMain.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (!isLogined() && mFragmentList.get(position) instanceof ShopCarfragment
                        ) {
                    mVpMain.post(() -> {//延时执行 防止切换回去的画面 不友好
                        mVpMain.setCurrentItem(mNowPager);
                        isLoginedGo();
                    });
                    return;
                }
                if (mFragmentList.get(position) instanceof ShopCarfragment) {
                    mShopCarfragment.getData();
                }
                if (mFragmentList.get(position) instanceof HomePageFragment) {
                    mHomePageFragment.ref();
                }
                if (mFragmentList.get(position) instanceof Mefragment) {
                    if(isLogined()){
                        ((Mefragment) mFragmentList.get(position)).getuserinfo();
                    }
                }
                mNowPager = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mTlMain.setupWithViewPager(mVpMain);

        for (int i = 0; i < selector.length; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.main_tab_item, null, false);
            ImageView iv = (ImageView) view.findViewById(R.id.tab_iv);
            RelativeLayout rel = (RelativeLayout) view.findViewById(R.id.rel);
            iv.setImageResource(selector[i]);
            TextView tv = (TextView) view.findViewById(R.id.tab_tv);
            tv.setText(mTitles[i]);
            tv.setTextColor((ColorStateList) getResources().getColorStateList(R.color.main_tab_tv_color));
            tv.setText(mTitles[i]);
            mTlMain.getTabAt(i).setCustomView(view);
            if (i == 2) {
                mBadgeView = new BadgeView(this);
                mBadgeView.setBackground(10, 0xFFFF0000);//色
                mBadgeView.setTargetView(rel);
            }else if(i == 3){
                mBadgeView2 = new BadgeView(this);
                mBadgeView2.setBackground(10, 0xFFFF0000);//色
                mBadgeView2.setTargetView(rel);
            }
        }

        mVpMain.setOffscreenPageLimit(mFragmentList.size());

        mVpMain.setCurrentItem(mFirstShowPage);//首次显示 商城首页
    }

    @Override
    protected void onResume() {
        super.onResume();
        MEMBERID = SharedPreferenceUtil.getSharedStringData(this, "memberId");
        ApiDataRepository.getInstance().getShopSetting(null, new ApiNetResponse<SettingBean>() {
            @Override
            public void onSuccess(SettingBean data) {
                MANJIAN = data.mianfei;
                PEISONGFEI = data.song_money;
                QISONG = data.qisong;
            }
        });

        ApiDataRepository.getInstance().getUserInfo(null, new ApiNetResponse<Account>() {
            @Override
            public void onSuccess(Account data) {
                if((data.notice_count+data.daifu+data.daisong+data.peisong+data.tui) == 0){
                    mBadgeView2.setVisibility(View.GONE);
                    return;
                }
                mBadgeView2.setVisibility(View.VISIBLE);
                mBadgeView2.setText((data.notice_count+data.daifu+data.daisong+data.peisong+data.tui)+"");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CrashManager.uninstall();
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }


    private void install() {
        CrashManager.install(new CrashManager.ExceptionHandler() {
            @Override
            public void handlerException(final Thread thread, final Throwable throwable) {

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            if (null != throwable) {
                            }
                            if (BuildConfig.DEBUG) {
                                Toast.makeText(MainActivity.this, "处理异常", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Throwable e) {

                        }
                    }
                });
            }
        });
    }

    /**
     * 是否登录中
     *
     * @return
     */
    protected boolean isLogined() {//是否已登录
        if (null == MEMBERID || TextUtils.isEmpty(MEMBERID)) {//未登录状态
            return false;
        } else {
            return true;
        }
    }

    protected boolean isLoginedGo() {//是否已登录
        if (null == MEMBERID || TextUtils.isEmpty(MEMBERID)) {//未登录状态
            startActivity(new Intent(this, LoginActivity.class));
            return false;
        } else {
            return true;
        }
    }

    private long mPressedTime = 0;

    long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else{
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
